﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ArithemeticSolver
{
	internal class InputParser
	{
		private readonly string m_input;

		private Queue<string> m_inputElements;
		private List<string> m_results;

		public InputParser(string input)
		{
			m_input = input;
		}

		public string[] Parse()
		{
			InitializeMembers();

			while (IsEnd() == false)
			{
				if (IsSpace())
				{
					GoNext();
					continue;
				}

				if (IsNumber()) LoadNumberString();
				else LoadOperatorString();
			}

			return GetResult();
		}

		private void GoNext()
		{
			m_inputElements.Dequeue();
		}

		private string[] GetResult()
		{
			return m_results.ToArray();
		}

		private void InitializeMembers()
		{
			m_results = new List<string>();
			m_inputElements = new Queue<string>(m_input.ToCharArray().Select(c => new string(c, 1)));
		}

		private void LoadOperatorString()
		{
			string operatorString = PopCurrentString();
			m_results.Add(operatorString);
		}

		private void LoadNumberString()
		{
			var builder = new StringBuilder();

			do
			{
				builder.Append(PopCurrentString());
			} while (!IsEnd() && IsNumber());

			m_results.Add(builder.ToString());
		}

		private bool IsSpace()
		{
			var current = PeekCurrentString();
			return Regex.IsMatch(current, @"\s");
		}

		private bool IsNumber()
		{
			string current = PeekCurrentString();
			return Regex.IsMatch(current, "[0-9]");
		}

		private string PeekCurrentString()
		{
			return m_inputElements.Peek();
		}

		private string PopCurrentString()
		{
			return m_inputElements.Dequeue();
		}

		private bool IsEnd()
		{
			return m_inputElements.Count == 0;
		}
	}
}